package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.AddressBookBusinessException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        // 向菜品表插入数据
        dishMapper.insert(dish);

        //获取新插入的菜品的id
        Long id = dish.getId();

        //向口味表插入数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
            }
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        //判断是否有起售中的菜品
        Long count = dishMapper.countEnableDishByIds(ids);
        if(count > 0){
            throw new AddressBookBusinessException(MessageConstant.DISH_ON_SALE);
        }
        // 判断是否关联了套餐
        List<Long> setmealIds = setmealDishMapper.coutByDishIds(ids);
        if(!CollectionUtils.isEmpty(setmealIds)){
            throw new AddressBookBusinessException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品，删除菜品口味
        dishMapper.deleteBatch(ids);
        dishFlavorMapper.deleteByDishId(ids);
    }

    /**
     * 根据id查询页面回显
     * @param id
     * @return
     */
    @Transactional
    @Override
    public DishVO getInfo(Long id) {
        //1.根据id查询菜品的基本信息
        Dish dish = dishMapper.getById(id);
        //2.根据id查询菜品口味信息 List<DishFlavor>
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //3.组装数据
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        if(dishFlavors != null){
            dishVO.setFlavors(dishFlavors);
        }
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        //1.根据id修改菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.update(dish);
        //2.根据id修改菜品口味信息(先删除后插入) Collections.singletonList(dish.getId())转为单个集合
        dishFlavorMapper.deleteByDishId(Collections.singletonList(dish.getId()));
        List<DishFlavor> flavors = dishDTO.getFlavors();

        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());
        }
        if (!CollectionUtils.isEmpty(flavors)) {
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    /**
     * 启售停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();

        dishMapper.update(dish);

        // 如果关联了套餐，则连同套餐一起停售
        if(status == StatusConstant.DISABLE){
            //判断是否关联了套餐
            List<Long> setmealIds = setmealDishMapper.coutByDishIds(Collections.singletonList(id));
            if(setmealIds != null && setmealIds.size() > 0){
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = Setmeal.builder()
                            .id(setmealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }

     /**
     * 根据分类id查询菜品
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //查询菜品数据
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO>  dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = getInfo(d.getId());
            dishVOList.add(dishVO);

        }

        return  dishVOList;
    }
}
